package com.epam.weblibrary.controllers;

import com.epam.weblibrary.entities.book.Book;
import com.epam.weblibrary.entities.order.Order;
import com.epam.weblibrary.entities.user.User;
import com.epam.weblibrary.service.book.BookService;
import com.epam.weblibrary.service.order.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Iurii_Miedviediev on 9/17/2014.
 */
@Controller
@RequestMapping("/cart")
@SessionAttributes({"cart"})
public class CartController {

    @Autowired
    BookService bookService;

    private static final int MAX_BOOKS_TAKEN = 5;

    @RequestMapping(params = "create", method = RequestMethod.GET)
     public String addBookToCart(@RequestParam("id") Long bookId, @AuthenticationPrincipal User user,
                             @ModelAttribute("cart") List<Book> cart, Model model) {

        for(Book book : cart) {
            if(book.getId().equals(bookId)) {
                model.addAttribute("error", "You already have this item in your cart");
                return getBookList(model, user, cart);
            }
        }

        if(cart.size() + user.getBooksTaken() >= MAX_BOOKS_TAKEN) {
            model.addAttribute("maxTakenError", "The amount of taken books must not exceed 5");
            return getBookList(model, user, cart);
        }

        Book book = bookService.find(bookId);
        cart.add(book);
        return "redirect:cart";
    }

    @RequestMapping(params = "remove", method = RequestMethod.GET)
    public String removeBookFromCart(@RequestParam Long id, @ModelAttribute("cart") List<Book> cart) {
        for(int i = 0; i < cart.size(); i++) {
            if(cart.get(i).getId().equals(id)) {
                cart.remove(i);
            }
        }
        return "redirect:cart";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String getBookList(Model model, @AuthenticationPrincipal User user, @ModelAttribute("cart") List<Book> cart) {

        Long totalPrice = 0L;
        for(Book book : cart) {
            totalPrice += book.getPrice();
        }

        model.addAttribute("total", totalPrice);
        model.addAttribute("discount", Math.round(totalPrice - totalPrice * user.getDiscount()));
        return "order/shoppingcart";
    }
}
